package com.atguigu.exam.service.impl;


import com.atguigu.exam.entity.Category;
import com.atguigu.exam.entity.Question;
import com.atguigu.exam.mapper.CategoryMapper;
import com.atguigu.exam.mapper.QuestionMapper;
import com.atguigu.exam.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.LongStream;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 获取所有的分类列表(包含题目数量)
     * @return
     */
    @Override
    public List<Category> getCategories() {
        //获取所有的分类列表，按sort排序
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        //获取每个分类下的题目数量
        getQuestionCount(categories);
        return categories;
    }

    //获取每个分类下的题目数量的方法
    private void getQuestionCount(List<Category> categories) {
        List<Map<Long,Long>>  countList=questionMapper.getCount();
        //将countList转成Map<Long,Long>
        Map<Long, Long> countMap = countList.stream().collect(Collectors.toMap(map -> map.get("category_id"), map -> map.get("count")));
        //遍历categories，给每个题目设置count
        categories.forEach(category -> {
            Long questionCount = countMap.getOrDefault(category.getId(), 0L);
            category.setCount(questionCount);
        });
    }


    /**
     * 获取分类树结构
     * @return
     */
    @Override
    public List<Category> getCategoryTree() {
        //获取所有的分类列表，按sort排序
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        //获取每个分类下的题目数量
        getQuestionCount(categories);
        //构建分类树结构
        List<Category> categoryTree=buildCategoryTree(categories);
        return categoryTree;
    }

    //构建分类树结构的方法
    private List<Category> buildCategoryTree(List<Category> categories) {
        //根据parentId进行分组，获取父分类下的子分类列表
        Map<Long, List<Category>> parentMap = categories.stream().collect(Collectors.groupingBy(Category::getParentId));
        //遍历所有的分类
        categories.forEach(category -> {
            //获取当前分类id
            Long id = category.getId();
            //根据当前分类id获取子分类列表
            List<Category> childrenCategories = parentMap.getOrDefault(id, new ArrayList<>());
            //将子分类放入当前分类中
            category.setChildren(childrenCategories);
            //获取当前类型的题目数量
            Long count = category.getCount();
            //获取所有子分类的题目数量之和
            Long childrenCount = childrenCategories.stream().mapToLong(c -> c.getCount() != null ? c.getCount() : 0L).sum();
            //当前分类的题目数量是子分类题目数量与当前类型的题目数量之和
            category.setCount(childrenCount + count);
        });
        //获取parentId为0的分类列表
        List<Category> catergoryTree = categories.stream().filter(category -> category.getParentId() == 0).collect(Collectors.toList());
        return catergoryTree;
    }

    //添加分类  思路：根据父分类id和当前类的名字查询父分类下是否有相同的名字
    @Override
    public void addCategory(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getParentId,category.getParentId()).eq(Category::getName,category.getName());
        Category isExistCategory = baseMapper.selectOne(categoryLambdaQueryWrapper);
        if(isExistCategory!=null){
            throw new RuntimeException("该分类已存在");
        }
        baseMapper.insert(category);
    }

    //更新分类  思路：在同一父类中，更新后的名字在父类中不存在，才能更新成功，如果更新的名字没有变，也可以更新成功
    @Override
    public void updateCategory(Category category) {
        LambdaUpdateWrapper<Category> categoryLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //查询父类id，确保是在同一父类下
        categoryLambdaUpdateWrapper.eq(Category::getParentId,category.getParentId())
                //查询名字，确保是同一个名字
                .eq(Category::getName,category.getName())
                //查询id，确保不是同一个id
                .ne(Category::getId,category.getId());
        boolean isExist = baseMapper.exists(categoryLambdaUpdateWrapper);
        if(isExist){
            throw new RuntimeException("该分类已存在");
        }
        baseMapper.updateById( category);
    }

    //删除分类  思路：分类下有题目或者有子分类，不能删除
    @Override
    public void deleteCategory(Long id) {
        Long categoryCount = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id));
        Long questionCount = questionMapper.selectCount(new LambdaQueryWrapper<Question>().eq(Question::getCategoryId, id));
        if(categoryCount>0||questionCount>0){
            throw new RuntimeException("该分类下有子分类或者题目，不能删除");
        }
        baseMapper.deleteById(id);
    }


}